package demo.practice.leetcode;

public class P98 {

    //https://leetcode-cn.com/problems/validate-binary-search-tree/

    //      10
    //    5   15
    //       6  20

    //[10,5,15,null,null,6,20]

    public static void main(String[] args) {
        TreeNode r = new TreeNode(2147483647);
//        r.left = new TreeNode(5);
//        r.right = new TreeNode(15);
//        r.right.right = new TreeNode(20);
//        r.right.left = new TreeNode(6);

        P98 p98 = new P98();
        boolean validBST = p98.isValidBST(r);
        System.out.println(validBST);
    }


    public boolean isValidBST(TreeNode root) {

        return isValidBST(root,Long.MAX_VALUE,Long.MIN_VALUE);

    }


    //[3,1,5,0,2,4,6,null,null,null,3]

        //      3
        //   1      5
        // 0   2  4   6
      //  n n n 3

    //[2147483647]

    public boolean isValidBST(TreeNode root,Long max,Long min){
        if(root==null){
            return true;
        }
        if( root.val>=max|| root.val<=min  )
            return false;
        if(root.right!=null){
            if(root.val >=root.right.val )
                return false;

            if(!isValidBST(root.right,max,Long.valueOf(root.val))){
                return false;
            }
        }
        if(root.left!=null){
            if(root.val <=root.left.val )
                return false;

            if(!isValidBST(root.left,Long.valueOf(root.val),min))
                return false;
        }
        return true;
    }


}
